package com.perceptivesoftware.licensing.server.handler;

import java.io.IOException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import com.perceptivesoftware.licensing.client.common.util.ClientConstants;
import com.perceptivesoftware.licensing.server.util.SessionServiceUtil;
import com.perceptivesoftware.login.client.LoginClientConstants;

@Controller
@Transactional
public class LoginRedirectHandler
{
	private final Log logger = LogFactory.getLog(getClass());

	@Autowired
	SessionServiceUtil sessionServiceUtil;

	@RequestMapping("/handler/LoginRedirect")
	public void redirectToHome(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		final String preserveDevMode = (request.getQueryString() == null) ? "" : "?" + request.getQueryString();
		if (sessionServiceUtil.isValidUser())
		{
			response.sendRedirect("../" + ClientConstants.LICENSING_URL + preserveDevMode);
		}
		else
		{
			final String msg = "User " + sessionServiceUtil.getUsername() + " authenticated but is not a valid user.";
			logger.warn(msg);
			final Cookie monster = new Cookie(LoginClientConstants.LOGIN_FAILURE_REASON_COOKIE, msg);
			monster.setPath("/");
			monster.setMaxAge(-1);
			response.addCookie(monster);
			response.sendRedirect(ClientConstants.LOGOUT_URL);
		}
	}


}
